package com.health.work.activity;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.health.work.R;
import com.health.work.model.CaseBean;
import com.health.work.utils.AsyncImageLoader;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UploadUtil;
import com.health.work.utils.UserInfoUtils;

/**
 * 病例储存页面
 * 
 * @author star
 * 
 */
public class CaseStorageActivity extends Activity {

	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	protected static final int SUCCES = -1;
	protected static final int SUCCESS = 0;
	protected static final int FAILE = 1;
	protected static final int ERROR = 2;
	private final static int NODATA = 3;
	private final static int GSUCCESS = 4;
	private File mCurrentPhotoFile;// 照相机拍照得到的图片

	private Thread thread;
	private String mobilePhoneNum;
	private String MedicalName;
	private String IsOpen = "false";
	private String url = "";
	private String remark;
	private EditText nameEditText;
	private EditText descriptionEditText;
	private CheckBox checkBox;
	private String name;
	private String description;
	private GridView grid;
	private ArrayList<CaseBean>caseList;
	private TextView nodata;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCES:
				GetMedicalRecord();
				nameEditText.setText("");
				descriptionEditText.setText("");
				checkBox.setChecked(false);
				TipsUtil.showAlert(CaseStorageActivity.this, null,
						"恭喜你，病例上传成功！");
				
				break;
			case FAILE:
				Toast.makeText(CaseStorageActivity.this, "病例上传失败！", Toast.LENGTH_SHORT).show();
				break;
			case SUCCESS:
				if (photo != null) {
					camera.setImageBitmap(photo);
				}
				break;
			case ERROR:
				Toast.makeText(CaseStorageActivity.this, "上传图片失败！", Toast.LENGTH_SHORT).show();
				break;
				
			case GSUCCESS:
				proAdapter adapter=new proAdapter(CaseStorageActivity.this);
				grid.setAdapter(adapter);
				break;
			case NODATA:
				grid.setVisibility(View.GONE);
				nodata.setVisibility(View.VISIBLE);
				break;
			default:
				break;
			}

		}

	};

	private String str_img = "";

	private Button back, upData;

	private ImageView camera;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.case_storage_layout);
		mobilePhoneNum = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		initPages();
		GetMedicalRecord();
	}

	private void initPages() {
		nodata=(TextView)findViewById(R.id.nodata);
		grid=(GridView)findViewById(R.id.brand_grid);
		back = (Button) findViewById(R.id.btnBack);
		back.setOnClickListener(onClickListener);
		camera = (ImageView) findViewById(R.id.camera);
		camera.setOnClickListener(onClickListener);
		upData = (Button) findViewById(R.id.btnUp);
		nameEditText = (EditText) findViewById(R.id.name);
		descriptionEditText = (EditText) findViewById(R.id.real);
		checkBox = (CheckBox) findViewById(R.id.isCheckBox);
		upData.setOnClickListener(onClickListener);
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String picName=caseList.get(arg2).Photos;
				Intent intent;
				intent=new Intent(CaseStorageActivity.this, BigImageActivity.class);
				intent.putExtra("picName", picName);
				startActivity(intent);
			}
		});
	}

	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.camera:
				doPickPhotoAction();
				break;
			case R.id.btnUp:
				name = nameEditText.getText().toString();
				description = descriptionEditText.getText().toString();
				isOpen();
				if (!"".equals(name) && !"".equals(description)
						&& !"".equals(url)) {
					getData();
				} else {
					if ("".equals(name)) {
						Toast.makeText(CaseStorageActivity.this, "请输入病例名称",
								Toast.LENGTH_SHORT).show();
					} else if ("".equals(description)) {
						Toast.makeText(CaseStorageActivity.this, "请输入病例说明",
								Toast.LENGTH_SHORT).show();
					} else if ("".equals(url)) {
						Toast.makeText(CaseStorageActivity.this, "请上传病例图片",
								Toast.LENGTH_SHORT).show();
					} else {

					}
				}
				break;
			default:
				break;
			}
		}

	};

	private Bitmap photo;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 
	 */
	/**
	 * 
	 * 88888888888888888888888888888888888888888888888888888888888888888888888888
	 */

	// 以下代码是调用摄像头或者系统相册
	public void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices;
		choices = new String[2];
		choices[0] = "拍照"; // 拍照
		choices[1] = "从相册中选择"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("选择方式");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0: {
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							} else {
								Toast.makeText(CaseStorageActivity.this,
										"出现异常", Toast.LENGTH_LONG).show();
							}
							break;

						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("CaseStorageActivity", "1:" + requestCode + "  2:" + resultCode);
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
			photo = data.getParcelableExtra("data");
			System.out.println(photo);
			camera.setImageBitmap(photo);
			// String imageStr = BitmapBase64.getBitmapStringBase64(photo);
			upFile(1, null, photo);
			break;
		}
		case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			// doCropPhoto(mCurrentPhotoFile);
			photo = BitmapFactory.decodeFile(mCurrentPhotoFile.getPath());
			// photo=mCurrentPhotoFile;
			upFile(2, mCurrentPhotoFile, null);
			break;
		}
		}
	}

	protected void upFile(final int kind, final File file, final Bitmap bitmap) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {
			private ProgressDialog dialog2 = null;

			@Override
			protected void onPreExecute() {
				if (dialog2 != null) {
				} else {
					dialog2 = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog2.setCancelable(true);
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (kind == 2) {
					url = UploadUtil.uploadFile(file, HEALTHPASSPORT.URL_PIC,
							"file");
				} else {
					url = UploadUtil.uploadFile(bitmap, HEALTHPASSPORT.URL_PIC,
							"file");
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				dialog2.dismiss();
				dialog2 = null;
				if (url != null && url.length() > 0) {
					handler.sendEmptyMessage(SUCCESS);
					str_img = str_img + url + ";";
					Log.e("img str", str_img);
				} else {
				}
			}
		};
		asyncLoad.execute(null);
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			mCurrentPhotoFile = new File(PHOTO_DIR, "health.jpg");// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	private void getData() {

		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new RequestParamtersUtil().SaveMedicalRecord(mobilePhoneNum,
						MedicalName, IsOpen, url, remark,
						new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								// TODO Auto-generated method stub
								if ("0".equals(result)) {
									handler.sendEmptyMessage(SUCCES);
								} else if ("1".equals(result)) {
									handler.sendEmptyMessage(FAILE);
								} else {
									handler.sendEmptyMessage(FAILE);
								}
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								// TODO Auto-generated method stub

							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								// TODO Auto-generated method stub

							}
						});
			}
		});
		thread.start();
	}

	
	private void GetMedicalRecord() {
		// TODO Auto-generated method stub
		thread=new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				new RequestParamtersUtil().GetMedicalRecord(mobilePhoneNum, "", new DefaultJSONData() {
					
					@Override
					public void parse(String result) throws JSONException {
						// TODO Auto-generated method stub
						if ("0".equals(result)) {
							handler.sendEmptyMessage(NODATA);
						} 
					}
					
					@Override
					public void parse(JSONObject object) throws JSONException {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void parse(JSONArray array) throws JSONException {
						// TODO Auto-generated method stub
						if(array.toString()!=null&&array.length()>0){
							caseList=new ArrayList<CaseBean>();
							for (int i = 0; i < array.length(); i++) {
								CaseBean bean=new CaseBean();
								bean.Id=array.getJSONObject(i).getInt("Id");
								bean.MobilePhone=array.getJSONObject(i).getString("MobilePhone");
								bean.MedicalName=array.getJSONObject(i).getString("MedicalName");
								bean.Photos=array.getJSONObject(i).getString("Photos");
								bean.Remark=array.getJSONObject(i).getString("Remark");
								bean.Date=array.getJSONObject(i).getString("Date");
								bean.IsOpen=array.getJSONObject(i).getBoolean("IsOpen");
								caseList.add(bean);
							}
							handler.sendEmptyMessage(GSUCCESS);
						}
					}
				});
			}
		});
		thread.start();
	}

	private void isOpen() {
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					IsOpen = "true";
				} else {
					IsOpen = "false";
				}
			}
		});
	}
	
	private class proAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private AsyncImageLoader asyncImageLoader;
		Activity context;

		public proAdapter(Context context) {
			this.context = (Activity) context;
			asyncImageLoader = new AsyncImageLoader();
			inflater = this.context.getLayoutInflater();
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return caseList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return caseList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHodler;
			if (convertView == null) {
				viewHodler = new ViewHolder();
				convertView = inflater.inflate(R.layout.grid_item,
						parent, false);
				viewHodler.headImageView=(ImageView)convertView.findViewById(R.id.brand_grid_Image);
				viewHodler.nameTextView=(TextView)convertView.findViewById(R.id.brand_grid_Text);
			} else {
				viewHodler = (ViewHolder) convertView.getTag();
			}
			CaseBean bean=caseList.get(position);
			if (bean.Photos != null) {
				Drawable drawable = asyncImageLoader
						.loadImageFromUrl(bean.Photos);
				if (drawable != null) {
					viewHodler.headImageView.setImageDrawable(drawable);
				} else {
					viewHodler.headImageView
							.setImageResource(R.drawable.nophoto);
				}
			}
			viewHodler.nameTextView.setText(bean.MedicalName);
			convertView.setTag(viewHodler);
			return convertView;
		}

	}
	class ViewHolder {
		public ImageView headImageView;
		public TextView nameTextView;
	}
}
